package com.briup.mt.web.controller;

import com.briup.mt.bean.Comment;
import com.briup.mt.service.ICommentService;
import com.briup.mt.utils.ExcelUtils;
import com.briup.mt.utils.Message;
import com.briup.mt.utils.MessageUtil;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.NotNull;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@RestController
@RequestMapping("/comment")
@Validated

public class CommentController {
    @Resource
    private ICommentService commentService;

    @ApiOperation(value = "导入到Excel中", notes = "注意！测试的时候请将地址粘贴到浏览器地址栏测试", produces = "comment/octet-stream")
    @GetMapping("download")
    @ApiImplicitParams({
            @ApiImplicitParam(name  = "content", value = "评论内容", paramType = "query"),
    })
    public void download(HttpServletResponse response, String content) throws Exception {
        // 1. 查询数据
        List<Comment> list = commentService.query(content);
        // 2. 将数据填充excel导出
        // 2.1 excel头部数据
        String[] headList = new String[] { "评论内容", "评论时间", "评论楼层", "评论状态" };
        // 2.2 属性
        String[] fieldList = new String[] { "content", "commentTime", "floor", "status"};
        // 2.3 数据列，需要转化
        List<Map<String, Object>> dataList = new ArrayList<>();
        for (Comment app : list) {
            // 每一个map相当于是一行数据，一行数据中多列
            Map<String, Object> map = new HashMap<>();
            map.put("content", app.getContent());
            map.put("commentTime",app.getCommentTime());
            map.put("floor",app.getFloor());
            map.put("status",app.getStatus());
            // dataList表示所有行
            dataList.add(map);
        }
        // 2.4 导出文件名
        String excelName = "comment";
        // 3. 调用工具方法导出Excel
        ExcelUtils.createExcel(response, excelName, headList, fieldList, dataList);

    }

    @GetMapping("query")
    public Message query(String content){
        List<Comment> list = commentService.query(content);
        return MessageUtil.success(list);
    }

    @PostMapping("saveOrUpdate")
    public  Message saveOrUpdate(Comment comment){
        commentService.saveOrUpdate(comment);
        return MessageUtil.success("操作成功");
    }

    @DeleteMapping("/deleteById")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id",value = "评论编号",required = true,paramType = "query")
    })
    public Message deleteById(@NotNull Long id){
        commentService.deleteById(id);
        return MessageUtil.success("删除成功");
    }
    }

